package com.baoteng.rbspy.service.impl;

import java.io.IOException;

import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baoteng.rbspy.config.car.RbSysConfig;
import com.baoteng.rbspy.config.car.URLConfig;
import com.baoteng.rbspy.model.response.ResponseModel;
import com.baoteng.rbspy.service.OkHttpClientService;
import com.baoteng.rbspy.util.JsonUtils;
import com.baoteng.rbspy.util.JsoupUtil;
import com.fasterxml.jackson.core.type.TypeReference;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

@Service(value = "noRedirectHttpClient")
public class OkHttpClientNoRedirectServiceImpl implements OkHttpClientService {
	private final Logger LOGGER = LoggerFactory.getLogger(OkHttpClientService.class);

	@Autowired
	protected OkHttpClient okHttpClient;

	@Autowired
	RbSysConfig rbSysConfig;

	@Autowired
	URLConfig urlConfig;

	@Override
	public boolean logout() {
		return false;
	}

	/**
	 * 登陆核心业务系统
	 */
	@Override
	public boolean login() {
		return false;
	}

	/**
	 * 登陆车险系统
	 */
	@Override
	public boolean carlogin() {
		return false;
	}

	/**
	 * 登陆客户管理系统
	 */
	@Override
	public boolean ciflogin() {
		return false;
	}

	@Override
	public boolean isOnline() {
		return false;
	}

	@Override
	public boolean isCarOnline() {
		return false;
	}

	@Override
	public boolean isCifOnline() {
		return false;
	}

	@Override
	public boolean cbclogin() {
		return false;
	}
	
	@Override
	public <T> ResponseModel<T> getJson(String url, TypeReference<T> typeReference) {
		ResponseModel<T> _response = new ResponseModel<T>();
		_response.setCode("503");
		try {
			Request request = new Request.Builder().url(url).build();
			Response response = okHttpClient.newCall(request).execute();
			_response = jsonParser(_response, response, typeReference);
		} catch (IOException e1) {
			LOGGER.error("httpclient getJson error", e1);
			_response.setCode("500");
		}
		return _response;
	}

	@Override
	public <T> ResponseModel<T> postJson(String url, String content, TypeReference<T> typeReference) {
		ResponseModel<T> _response = new ResponseModel<T>();
		_response.setCode("503");
		try {
			if(content!=null ) content = content.replaceAll("(\r\n|\r|\n|\n\r)", "");
			Request request = new Request.Builder()
					.url(url).post(RequestBody
							.create(MediaType.parse("application/x-www-form-urlencoded; charset=UTF-8"), content))
					.build();
			Response response = okHttpClient.newCall(request).execute();
			_response = jsonParser(_response, response, typeReference);
		} catch (IOException e) {
			LOGGER.error("httpclient postJson error", e);
			_response.setCode("500");
		}

		return _response;
	}

	@Override
	public <T> ResponseModel<T> postJson(String url, RequestBody body, TypeReference<T> typeReference) {
		ResponseModel<T> _response = new ResponseModel<T>();
		_response.setCode("503");
		try {
			Request request = new Request.Builder().url(url).post(body).build();
			Response response = okHttpClient.newCall(request).execute();
			_response = jsonParser(_response, response, typeReference);
		} catch (IOException e) {
			LOGGER.error("httpclient postJson error", e);
			_response.setCode("500");
		}

		return _response;
	}

	private <T> ResponseModel<T> jsonParser(ResponseModel<T> _response, Response response,
			TypeReference<T> typeReference) {
		try {
			if (response != null && response.isSuccessful() || response.code()==302 || response.code()==301) {
				_response.setCode("200");
				String strBody = response.body().string();
				if (StringUtils.isNotBlank(strBody)) {
					strBody = strBody.trim();
					if (strBody.startsWith("{") || strBody.startsWith("[")) {
						LOGGER.info(strBody);
						_response.setBody(JsonUtils.parseJson(strBody, typeReference));
					} else {
						_response.setBody(null);
					}
				}
			}
		} catch (IOException e) {
			LOGGER.error("httpclient jsonParser error", e);
			_response.setCode("500");
		}
		return _response;
	}

	@Override
	public <T> ResponseModel<T> getHtml(String url, Class<T> clazz) {
		ResponseModel<T> _response = new ResponseModel<T>();
		_response.setCode("503");
		try {
			Request request = new Request.Builder().url(url).build();
			Response response = okHttpClient.newCall(request).execute();
			_response = htmlParser(_response, response, clazz);
		} catch (IOException e) {
			LOGGER.error("httpclient getHtml error", e);
			_response.setCode("500");
		}

		return _response;
	}

	@Override
	public <T> ResponseModel<T> postHtml(String url, String content, Class<T> clazz) {
		ResponseModel<T> _response = new ResponseModel<T>();
		_response.setCode("503");
		try {
			if(content!=null ) content = content.replaceAll("(\r\n|\r|\n|\n\r)", "");
			Request request = new Request.Builder()
					.url(url).post(RequestBody
							.create(MediaType.parse("application/x-www-form-urlencoded; charset=UTF-8"), content))
					.build();
			Response response = okHttpClient.newCall(request).execute();
			_response = htmlParser(_response, response, clazz);
		} catch (IOException e) {
			LOGGER.error("httpclient postHtml error", e);
			_response.setCode("500");
		}

		return _response;
	}

	@Override
	public <T> ResponseModel<T> postHtml(String url, RequestBody body, Class<T> clazz) {
		ResponseModel<T> _response = new ResponseModel<T>();
		_response.setCode("503");
		try {
			Request request = new Request.Builder().url(url).post(body).build();
			Response response = okHttpClient.newCall(request).execute();
			_response = htmlParser(_response, response, clazz);
		} catch (IOException e) {
			LOGGER.error("httpclient postHtml error", e);
			_response.setCode("500");
		}

		return _response;
	}

	@SuppressWarnings("unchecked")
	private <T> ResponseModel<T> htmlParser(ResponseModel<T> _response, Response response, Class<T> clazz) {
		try {
			if (response != null && (response.isSuccessful() || response.code()==302 || response.code()==301)) {
				_response.setCode("200");
				if(response.code()==302 || response.code()==301) {
					_response.setRedirectUrl(response.header("Location"));
				}
				String strBody = response.body().string();
				if (StringUtils.isNotBlank(strBody)) {
					LOGGER.info(strBody);
					T t = clazz.newInstance();
					if (t instanceof String) {
						_response.setBody((T) strBody.trim());
					} else {
						if (strBody.contains("<html")) {
							_response.setBody((T) JsoupUtil.newInstance().parse(Jsoup.parse(strBody.trim()), t));
						} else {
							_response.setBody(null);
						}
					}
				}
			}
		} catch (InstantiationException | IllegalAccessException | IOException e) {
			LOGGER.error("httpclient htmlParser error", e);
			_response.setCode("500");
		}
		return _response;
	}
}
